package com.originskyseed.platform.user.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.originskyseed.platform.common.utils.CsvUtil;
import com.originskyseed.platform.core.util.bean.ExportExcelUtil;
import com.originskyseed.platform.user.model.UserCumulativeCharge;
import com.originskyseed.platform.user.vo.request.UserCumulativeChargeRequestVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.user.i18n.UserResponseMsg;
import com.originskyseed.platform.user.model.Dept;
import com.originskyseed.platform.user.model.PlayerRelateConsume;
import com.originskyseed.platform.user.model.UserInfo;
import com.originskyseed.platform.user.service.IDeptService;
import com.originskyseed.platform.user.service.IPlayerRelateConsumeService;
import com.originskyseed.platform.user.service.IUserInfoService;
import com.originskyseed.platform.user.vo.request.PlayerRelateConsumeRequestVO;

/**
 * 玩家消费信息表Controller类（OSI_PLAYER_RELATE_CONSUME）
 *
 * @author wlj
 */
@Controller
@RequestMapping("/playerRelateConsume")
@BaseLocaleResource(localeFileName = "i18n_user")
public class PlayerRelateConsumeController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(PlayerRelateConsumeController.class);

	@DubboReference
	private IPlayerRelateConsumeService playerRelateConsumeService;

	@DubboReference
	private IDeptService deptService;

	@DubboReference
	private IUserInfoService userInfoService;

	/**
	 * 分页查询
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/playerRelateConsumeList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<PlayerRelateConsume>> playerRelateConsumeList(HttpServletRequest request) {
		BaseResponseBody<BasePage<PlayerRelateConsume>> result = null;
		try {
			// 请求对象
			PlayerRelateConsumeRequestVO requestVO = this.getParameterBean(PlayerRelateConsumeRequestVO.class);

			// 分页查询
			BasePage<PlayerRelateConsume> page = new BasePage<PlayerRelateConsume>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.playerRelateConsumeService.selectListByPage(requestVO.toMap(), page);
			result = new BaseResponseBody<BasePage<PlayerRelateConsume>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<PlayerRelateConsume>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 保存信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/playerRelateConsumeSave.json", method = RequestMethod.POST)
	@RequiredParams(names = {})
	public BaseResponseBody<PlayerRelateConsume> playerRelateConsumeSave(HttpServletRequest request) {
		BaseResponseBody<PlayerRelateConsume> result = null;
		try {
			// 请求对象
			PlayerRelateConsume playerRelateConsume = this.getParameterBean(PlayerRelateConsume.class);

			if (StringUtils.isNotBlank(playerRelateConsume.getId())) {
				this.playerRelateConsumeService.updateByPrimaryKey(playerRelateConsume);
			} else {
				this.playerRelateConsumeService.insertSelective(playerRelateConsume);
			}
			result = new BaseResponseBody<PlayerRelateConsume>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), playerRelateConsume);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<PlayerRelateConsume>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 删除信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/playerRelateConsumeDelete.json", method = RequestMethod.POST)
	@RequiredParams(names = { "ids" })
	public BaseResponseBody<Boolean> playerRelateConsumeDelete(HttpServletRequest request) {
		BaseResponseBody<Boolean> result = null;
		try {
			// 请求参数
			String[] ids = this.getParameterArray("ids", new String[] {});

			this.playerRelateConsumeService.deleteByPrimaryKeys(Arrays.asList(ids));
			result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 消费明细列表查询
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/consumptionDetailsList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody consumptionDetailsList(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 当前登录用户
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			String otherAccount=userInfo.getOtherAccount() == null ? "" : userInfo.getOtherAccount();
			// 请求对象
			PlayerRelateConsumeRequestVO requestVO = this.getParameterBean(PlayerRelateConsumeRequestVO.class);
			// 根据范围查询
			List<String> otherAccountList = new ArrayList<>();
			if(userInfo.getSourceSys()!=0) //开放类 查询所有信息
			{
				if (userInfo.getType() == 6 || userInfo.getType() == 11) {
					if (StringUtils.isNotBlank(otherAccount)) {
						otherAccountList.add(otherAccount);
					}
				} else {
					Dept dept = this.deptService.selectByPrimaryKey(userInfo.getDeptId());
					List<String> deptList = new ArrayList<>();
					if (dept != null) {
						selectSonId(dept.getCode(), deptList);
						otherAccountList = this.userInfoService.selectOtherAccountByDeptIds(deptList, 2);
					}
					if (StringUtils.isNotBlank(otherAccount)) {
						otherAccountList.add(otherAccount);
					}
				}
				if (otherAccountList.size() == 0) {
					return new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), new BasePage<PlayerRelateConsume>(requestVO.getPageNo(), requestVO.getPageSize()));
				}
				requestVO.setChannelSubIdList(otherAccountList);
			}
			// 分页查询
			BasePage<PlayerRelateConsume> page = new BasePage<PlayerRelateConsume>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.playerRelateConsumeService.selectConsumptionDetailsByPage(requestVO.toMap(), page);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}


	/**
	 * 导出信息Excel
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/export.json")
	public void logExport(HttpServletRequest request, HttpServletResponse response) {
		try {
			// 当前登录用户
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			String otherAccount=userInfo.getOtherAccount() == null ? "" : userInfo.getOtherAccount();
			// 请求对象
			PlayerRelateConsumeRequestVO requestVO = this.getParameterBean(PlayerRelateConsumeRequestVO.class);
			// 根据范围查询
			List<String> otherAccountList = new ArrayList<>();
			if(userInfo.getSourceSys()!=0) //开放类 查询所有信息
			{
				if (userInfo.getType() == 6 || userInfo.getType() == 11) {
					if (StringUtils.isNotBlank(otherAccount)) {
						otherAccountList.add(otherAccount);
					}
				} else {
					Dept dept = this.deptService.selectByPrimaryKey(userInfo.getDeptId());
					List<String> deptList = new ArrayList<>();
					if (dept != null) {
						selectSonId(dept.getCode(), deptList);
						otherAccountList = this.userInfoService.selectOtherAccountByDeptIds(deptList, 2);
					}
					if (StringUtils.isNotBlank(otherAccount)) {
						otherAccountList.add(otherAccount);
					}
				}
				if (otherAccountList.size() == 0) {
					return;
				}
				requestVO.setChannelSubIdList(otherAccountList);
			}

			List<PlayerRelateConsume> list = this.playerRelateConsumeService.selectConsumptionDetailsByMap(requestVO.toMap());

			Map<String, String> header = new LinkedHashMap<>();
			header.put("id", "ID");
			header.put("playerNickname", "玩家昵称");
			header.put("playerId", "玩家id");
			header.put("orderId", "消费订单");
			header.put("consumeTime", "消费时间");
			header.put("amount", "消费金额");
			header.put("anchorId", "送礼对象id");
			header.put("anchorNickname", "送礼对象");
			header.put("orderContent", "获得物品");
			CsvUtil.export(request, response, "消费明细", header, list);

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

	/**
	 * 输出Excel
	 *
	 * @param response
	 * @param title
	 * @param fileName
	 * @param sheetName
	 * @param values
	 * @throws IOException
	 */
	private void outPutExcel(HttpServletResponse response, String[] title, String fileName, String sheetName, String[][] values) throws IOException {
		// 创建HSSFWorkbook
		OutputStream os = null;
		try {
			HSSFWorkbook wb = ExportExcelUtil.getHSSFWorkbook(sheetName, title, values, null);
			// 将文件存到指定位置
			this.setResponseHeader(response, fileName);
			os = response.getOutputStream();
			wb.write(os);
			os.flush();
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {
			if (null != os) {
				try {
					os.close();
				} catch (IOException e) {
					logger.error(e.getMessage(), e);
				}
			}
		}

	}

	/**
	 * 发送响应流方法
	 *
	 * @param response
	 * @param fileName
	 */
	public void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(), "ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.error(e.getMessage(), e);
			}
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
			logger.error(ex.getMessage(), ex);
		}
	}


	/**
	 * 查询组织下的部门
	 *
	 * @param code
	 * @param list
	 * @throws Exception
	 */
	private void selectSonId(String code, List<String> list) throws Exception {
		List<Dept> deptList = this.deptService.selectByParentCode(code);
		if (deptList != null) {
			for (Dept dept1 : deptList) {
				list.add(dept1.getId());
				selectSonId(dept1.getCode(), list);
			}
		}
	}
}
